const API = (function () {
    const BASE_URL = "https://study.duyiedu.com"
    const TOKEN_KEY = 'token'

    async function get(path) {
        const headers = {}
        let token = localStorage.getItem(TOKEN_KEY)
        if (token) {
            headers.authorization = 'Bearer' + " " + token
        }
        return await fetch(BASE_URL + path, { headers })
    }
    async function post(path, bodyObj = {}) {
        const headers = {
            'Content-Type': 'application/json'
        }
        let token = localStorage.getItem(TOKEN_KEY)
        if (token) {
            headers.authorization = 'Bearer' + " " + token
        }
        return await fetch(BASE_URL + path, {
            method: "POST",
            headers,
            body: JSON.stringify(bodyObj)
        })
    }
    async function reg(userInfo) {
        const res = await fetch(BASE_URL + "/api/user/reg", {
            method: "POST",
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(userInfo)
        })
        return await res.json()
    }
    async function login(loginInfo) {
        const res = await fetch(BASE_URL + "/api/user/login", {
            method: "POST",
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(loginInfo)
        })
        const result = await res.json()
        if (result.code === 0) {
            console.log(res)
            localStorage.setItem(TOKEN_KEY, res.headers.get("authorization"))
        }
        return result
    }
    // 账号是否存在
    async function exists(loginId) {
        const res = await get("/api/user/exists?loginId=" + loginId)
        return await res.json()
    }
    async function profile() {
        const res = await get("/api/user/profile")
        return await res.json()
    }
    async function sendChat(content) {
        const res = await post("/api/chat", { content })
        return await res.json()
    }
    async function getHistory() {
        const res = await get("/api/chat/history")
        return await res.json()
    }
    function exit() {
        localStorage.removeItem(TOKEN_KEY)
    }
    return{
        reg,
        login,
        exists,
        profile,
        sendChat,
        getHistory,
        exit
    }
})()


